import { useMemo , useState } from 'react';
import { detailArticle ,likeArticle , likeNum } from '@/service/article'
import { useRequest } from 'ahooks'
import { usePageTitle } from '@/hooks'
import { useParams } from 'react-router-dom'
import { QRCode ,Tag , Avatar , message} from 'antd'
import { formatTime } from '@/utils'
import { EyeOutlined , LikeOutlined , WechatOutlined } from '@ant-design/icons'
import avatar from '@/assets/pngs/04.mobile-logo_.png'
import MarkDown from '@/components/markdown'

import './index.less'

export default function Detail() {

  usePageTitle("文章详情")

  const { id } = useParams<{ id: string }>();

  const { data } = useRequest(() => detailArticle({ id: Number(id) }));

  const { data: numOfLike, run: loadLike } = useRequest(() => likeNum({ id: Number(id) }))
  
  const [ hasLike , setHasLike ] = useState<boolean>(false)

  const children = useMemo(() => {
    return data?.content || ""
  }, [data])
  
  const like = async () => {
    if(hasLike) return message.warning("不可重复点赞")
    await likeArticle({ id: Number(id) });
    loadLike()
    setHasLike(true)
  }

  return (
      <div className="blog-detail">
        <div className="blog-tool">
          <div className="readed" data-badge={data?.read_num || 0}>
            <EyeOutlined />
          </div>
          <div className={`${hasLike ? 'active' : ''} thumbs`} data-badge={numOfLike || 0} onClick={like}>
            <LikeOutlined/>
          </div>
          <div className="share">
            <WechatOutlined />
            <div className="code">
            <QRCode value={location.href}/>
            </div>
          </div>
        </div>
        <div className="blog-front">
          <div className="blog-title">{ data?.title }</div>
          <div className="blog-time">
            <Avatar src={<img src={avatar} alt="avatar" />} />
            <span className="blog-createtime">{formatTime(data?.create_time)}</span>
            <span className="blog-badge">
              <Tag color="green">原创</Tag>
            </span>
          </div>
        </div>
        <MarkDown children={ children }/>
        <div className="blog-tool-mobile">
          <div className="readed">
            <EyeOutlined className="icon"/>
            <span>{data?.read_num || 0} </span>
          </div>
          <div className={`${hasLike ? 'active' : ''} thumbs`} onClick={like}>
            <LikeOutlined className="icon"/>
            <span>{numOfLike || 0}</span>
          </div>
        </div>
        <div className="blog-end">
          <div>作者：<span className="end-autor">Story</span></div>
          <div>更新：<span className="end-time">{ formatTime(data?.updated_time) || "" }</span></div>
          <div>
            标签：
            {(data?.tag || "").split(",").map(item => <Tag color="green" key={ item} >{item }</Tag>)}
          </div>
        </div>
      </div>
  )
}

